import React, {lazy} from 'react';
import {message, Popconfirm, Table, Tooltip} from "antd";
import "@/layouts/queryList.css";
import MyForm from "./MyForm";
import {DeleteOutlined, FormOutlined, FullscreenExitOutlined, FullscreenOutlined} from "@ant-design/icons";
import DicComponent from "./dicComponent";
import "./style.css"
import Utils from "../../utils";
// import LzModal from "../lzModal";
const LzModal = lazy(() => import('../lzModal'));

/**
 * **公用Component**
 * > 统一的格式：Form、Button、Table等，传入对应参数即可。
 * - `2025-07-03 16:31:55 tzj`
 * - 表单：form、增删改查、导出
 * - table：标题、tbody、分页器
 * - other：导出组件、增改组件
 * @author tzj
 * @Date 20250703
 * */
class BaseComponent extends DicComponent {
    constructor(props) {
        super(props);
        this.state = {
            // 加载中
            loading: false,
            // 列表数据，不加合计行的数据，在导出时使用Excel的SUM公式。
            dataList: [],
            // table展示的数据
            // dataSource: [],
            columns: [],
            // 接口返回data值
            resData: {
                // 当前页码
                current: 1,
                // 总页码
                pages: 1,
                searchCount: true,
                // 每页最多显示数量
                size: 50,
                // 总数据量
                total: 0,
                // 接口数据
                records: []
            },
            // 分页器配置
            pagination: {
                current: 1,
                // 默认每页显示条数
                defaultPageSize: 50,
                pageSize: 50,
                // 切换每页显示条数
                pageSizeOptions: [7, 10, 20, 50, 100]
            },
            // 要显示的form表单
            // formItemList:  ["fuzzy", "companies", "followState", "serviceWx", "serviceDy", "creator", "channel", "dateRange"],
            formItemList: [],
            // 显示的按钮【增删改查导：add、delete、edit、query、export】
            // buttons : ["query", "add", "edit", "export", "delete"]
            buttons: [],
            // 其他自定义btn
            btnOther: [],
            // 操作列其他自定义按钮
            editOther: [],
            // 有些页面特殊参数，用于查询接口
            params: {},
            // 对一条数据操作时，其key字段
            rowKey: "id",
            // 查询全部，查10000条，分页器只显示总条数。
            queryAll: false,
            // 添加求和行，需给columns不求和的字段设置sumName值。 如："合计"、""
            sumRow: false,
            // table固定表头用
            scrollY: window.innerHeight - 410,
            // table显示表头
            tableTitle: false,
            // table展开配置
            expandable: false,
            // 当前页 网页全屏
            fullScreen: false,
            // response没有code、data、msg格式，而是直接data
            resNormal: false,
        };
        if (this.hasLzModal) {
            this.LzModal = lazy(() => import('../lzModal'));
        }
    }

    pageLoad = true;
    tableBoxRef = React.createRef();
    form = React.createRef();
    lzModalRef = React.createRef();
    // 留资弹窗
    hasLzModal = false;

    // 求和行数据
    totals = [];

    set defaultPageSize(pageSize) {
        this.state.pagination.pageSize = pageSize;
        this.state.pagination.defaultPageSize = pageSize;
    }

    set columns(list) {
        list.forEach(item => {
            if (item.render) {
                const _render = item.render;
                item.render = (text, record) => {
                    return record.hidden ? text : _render(text, record)
                }
            }

            if (item.sorter) {
                if (item.sorter === true) {
                    const key = item["dataIndex"];
                    if (item.render) {
                        item.sorter = (a, b) => item.render(a[key], a) - item.render(b[key], b)
                    } else {
                        item.sorter = (a, b) => a[key] - b[key]
                    }
                }
                item.sortDirections = item.sortDirections || ['descend', 'ascend']
            }
        })
        this.state.columns = list;
    }

    // 查询的接口，子class覆盖
    queryApi() {
        console.error("此方法应该被覆盖：queryApi() return new Promise(resolve => resolve())");
        return new Promise(resolve => resolve());
    }

    // 删除的接口
    deleteApi() {
        console.error("此方法应该被覆盖：deleteApi() return new Promise(resolve => resolve())");
        return new Promise(resolve => resolve());
    }

    /*    // 添加求和行
        addSumRow = (list) => {
            if (!this.state.sumRow || list.length <= 1) return list;
            const {columns} = this.state;
            const rowData = {
                // isSumRow: true
            };
            columns.forEach(item => {
                rowData[item.dataIndex] = item.sumName === undefined ? 0 : item.sumName;
            })
            list.forEach(item => {
                columns.forEach(column => {
                    if (column.sumName === undefined) rowData[column.dataIndex] = Utils.addPrecise(rowData[column.dataIndex], Number(item[column.dataIndex]));
                })
            })
            console.log(rowData)
            this.sumRow = rowData
            list.push(rowData);
            return list;
        }*/

    // 设置合计行数据
    setSumRow = (list) => {
        /*
        这里加个标题行的目的：
        当整列没有数据时，header的宽度无法撑开
        固定width效果太差，minWidth在低版本antd设置无效，而升级antd太多兼容性问题。
        这里曲线救国，summary行加标题文字，让其撑开宽度，并于css设置其高度0以隐藏。
        2025-09-10 12:25:21 tzj
        * */
        const titles = []
        const sumList = []
        const {columns} = this.state;
        const rowData = {};
        if (this.state.sumRow) {
            columns.forEach(item => {
                rowData[item.dataIndex] = item.sumName === undefined ? 0 : item.sumName;
            })
            list.forEach(item => {
                columns.forEach(column => {
                    if (column.sumName === undefined) rowData[column.dataIndex] = Utils.addPrecise(rowData[column.dataIndex], item[column.dataIndex]);
                })
            })
        }

        columns.forEach(col => {
            titles.push(col.title);
            if (this.state.sumRow) {
                const val = rowData[col.dataIndex];
                sumList.push(col.render ? col.render(val, rowData) : val)
            }
        })
        this.totals = this.state.sumRow ? [titles, sumList] : [titles]
        // this.totals = [[]]
    }

    // 接口查询
    // paginated 默认分页查询
    queryDataList = (paginated = true) => {
        this.beforeQuery()
        const formData = {
            ...this.form.dataForm,
            ...this.state.params
        }
        const pagination = {
            current: this.state.pagination.current,
            pageSize: this.state.pagination.pageSize,
        }
        // 不分页视为查全部
        if (!paginated || this.state.queryAll) {
            // delete pagination.current;
            // delete pagination.pageSize;
            pagination.current = 1;
            pagination.pageSize = 10000;
        }
        this.setState({loading: true})
        return new Promise((resolve, reject) => {
            this.queryApi({formData, pagination})
                .then(res => {
                    const flag = this.state.resNormal;
                    if (res.code !== "1" && !flag) reject(res);
                    const resData = flag ? res : res.data
                    // 不分页：不更新Table
                    if (paginated || this.state.queryAll) {
                        const list = resData.records;
                        const dataList = this.dataProcess(list);
                        // const dataSource = this.addSumRow(dataList)
                        this.setSumRow(dataList)
                        this.setState({
                            resData,
                            dataList,
                            // dataSource,
                            loading: false
                        })
                    }
                    resolve(resData.records);
                })
                .catch(err => {
                    this.setState({loading: false})
                    reject(err);
                })
        })
    }

    beforeQuery = () => {
    }

    // 数据加工
    dataProcess(list) {
        return list
    }

    onTableChange = (data) => {
        let {current, pageSize} = data;
        // 没做分页的页面，有排序触发change，就不调接口了，简单实现。
        // 写法不严谨，若以后分页+排序，额外传sort字段并调接口
        if (!current) return;
        this.setState({
            pagination: {
                defaultPageSize: this.state.pagination.defaultPageSize,
                pageSizeOptions: this.state.pagination.pageSizeOptions,
                current,
                pageSize
            }
        }, () => {
            this.queryDataList();
        })
    }

    updateScrollY = () => {
        const thDom = this.tableBoxRef.querySelector(".ant-table-title");
        const thDomHeight = thDom ? thDom.clientHeight : 0;
        const delta = this.state.fullScreen ? 150 : 120;
        // 高度还是算不明白，将就用吧
        this.setState({
            scrollY: this.tableBoxRef.clientHeight - delta - thDomHeight
        })
    }

    // 在组件挂载完成后执行
    componentDidMount() {
        super.componentDidMount();
        this.form.dataInit(() => {
            if (this.pageLoad) this.queryDataList(!this.state.queryAll);
        })

        this.updateScrollY();
        window.addEventListener('resize', this.updateScrollY);

    }

    // 在组件更新时判断是否需要更新
    // 要么删除该方法，要么return boolean，否则异常
    // shouldComponentUpdate(nextProps, nextState) {
    //     // 示例：只有当count变化时才更新组件
    //     // return nextState.count !== this.state.count;
    // }

    // 在组件卸载前执行清理操作
    componentWillUnmount() {
        window.removeEventListener('resize', this.updateScrollY);
    }

    // 打开弹窗
    setHandler = (handler, record) => {
        if (this.EditItemRef) this.EditItemRef.showModal(handler, record);
    }

    // 删除一条数据
    deleteItem(record) {
        this.deleteApi(record[this.state.rowKey]).then(res => {
            if (res.code !== "1") {
                message.warning(res.msg || "未知异常！");
            } else {
                message.success(res.msg || "操作成功！");
                this.queryDataList()
            }
        })
    }

    // 增改弹窗
    EditItem = () => <div/>;

    // 双击table行触发事件
    onRowDoubleClick = (record) => {
        if (this.state.permission.review) {
            this.setHandler("view", record);
        }
    }

    onDoubleClick(record) {
        // if (record.isSumRow) return;// 合计行不要双击
        this.onRowDoubleClick(record);
    }

    // 切换全屏
    screenSwitch = () => {
        this.setState({
            fullScreen: !this.state.fullScreen
        }, () => {
            this.updateScrollY();
        })
    }

    summary = () => {
        return (
            <>
                {/*你可以通过配置 Table.Summary 的 fixed 属性使其固定(4.16.0 支持)*/}
                {/*<Table.Summary fixed>*/}
                {
                    this.totals.map((item, i) => {
                        return (
                            <Table.Summary.Row key={i}>
                                {Array.isArray(item) ? item.map((val, j) => {
                                    return (<Table.Summary.Cell index={j}>
                                        {val}
                                    </Table.Summary.Cell>)
                                }) : null}
                            </Table.Summary.Row>
                        )
                    })
                }
                {/*</Table.Summary>*/}
            </>
        )
    }

    // lzModal = () => {}

    // 每次setState触发render
    render() {
        const {
            dataList,
            // dataSource,
            loading,
            columns,
            resData,
            formItemList,
            btnOther,
            editOther,
            buttons,
            pagination,
            filename,
            fullScreen,
            sumRow,
            rowKey,
            deleteCustom
        } = this.state;
        const {defaultPageSize, pageSizeOptions} = pagination;
        const EditItem = this.EditItem;
        const pathname = this.props.location ? this.props.location.pathname : ''

        const myTitle = (title, tip) => {
            return tip ? <Tooltip placement="bottom" title={tip}>{title}</Tooltip> : title
        }

        const renderColumns = columns.map(item => {
            return {
                ...item,
                title: myTitle(item.title, item.tip)
            }
        });
        const EditIcon = ({record}) => buttons.includes('edit') ?
            <FormOutlined onClick={() => this.setHandler("update", record)} className='update-button'/> : null;
        const DeleteIcon = ({record}) => buttons.includes('delete') ? deleteCustom ?
                <DeleteOutlined className='delete-button' onClick={() => this.deleteItem(record)}/> :
                <Popconfirm title="确认删除?" onConfirm={() => this.deleteItem(record)}>
                    <DeleteOutlined className='delete-button'/>
                </Popconfirm>
            : null
        // const LzModal2 = this.lzModal;
        if (buttons.includes("edit") || buttons.includes("delete") || editOther.length) {
            renderColumns.push({
                title: '操作',
                fixed: 'right',
                key: 'action',
                render: (text, record) => {
                    return (
                        <span className='handleButton'>
                            <EditIcon record={record}></EditIcon>
                            <DeleteIcon record={record}></DeleteIcon>
                            {
                                editOther.length ? editOther.map((Item, i) => {
                                    return (<Item record={record} hoc={this}/>)
                                }) : null
                            }
                </span>)
                }
            })
        }

        return (
            <div className={"queryList" + (fullScreen ? " full-screen" : "")}>
                {/*  网页全屏  */}
                {
                    fullScreen ?
                        <FullscreenExitOutlined title="退出全屏" className="icon-screen" onClick={this.screenSwitch}/> :
                        <FullscreenOutlined title="网页全屏" className="icon-screen" onClick={this.screenSwitch}/>
                }

                <MyForm ref={form => this.form = form}
                        page={this}
                        formItemList={formItemList}
                        buttons={buttons}
                        btnOther={btnOther}
                        setHandler={this.setHandler}
                        queryDataList={this.queryDataList}
                        columns={columns}
                        filename={filename}
                        sumRow={sumRow}
                ></MyForm>

                <div className="tableBox" ref={box => this.tableBoxRef = box}>
                    <Table
                        id="table"
                        rowKey={(item, index) => item[rowKey] || item.id || item.key || index}
                        columns={renderColumns}
                        bordered={true}
                        dataSource={dataList}
                        // dataSource={dataSource}
                        scroll={{x: "max-content", y: this.state.scrollY}}
                        loading={loading}
                        size="middle"
                        style={{padding: '5px'}}
                        tableLayout="auto"
                        expandable={this.state.expandable}
                        pagination={this.state.queryAll ? false : {
                            total: resData.total,
                            defaultPageSize,
                            onShowSizeChange: (current, pageSize) => {
                                this.setState({
                                    pagination: {
                                        ...this.state.pagination,
                                        current,
                                        pageSize
                                    }
                                })
                            },
                            current: resData.current,
                            showQuickJumper: true,
                            pageSizeOptions,
                            showTotal: (total, range) => `共计 ${total} 条数据`,
                        }}
                        title={this.state.tableTitle && this.state.filename ? () => <h3>{filename}</h3> : null}
                        // footer={() => ''}
                        onChange={this.onTableChange}
                        onRow={record => {
                            return {
                                onDoubleClick: () => this.onDoubleClick(record)
                            }
                        }}
                        summary={list => this.summary(list)}
                    />
                </div>

                {EditItem ?
                    <EditItem ref={(ref) => this.EditItemRef = ref}
                              editItemDone={this.queryDataList}
                              bookRender={this.bookRender}
                    /> : null}

                {/*<this.LzModal ref={modal => this.lzModalRef = modal} key={pathname + "-lzModal"}></this.LzModal>*/}
                {/*<LzModal ref={modal => this.lzModalRef = modal} key={pathname + "-lzModal"}></LzModal>*/}

                {
                    this.hasLzModal ?
                        <LzModal ref={modal => this.lzModalRef = modal} key={pathname + "-lzModal"}></LzModal> : null
                }
            </div>
        );
    }
}

export default BaseComponent;